package com.chance.cc.crawler.development.scripts.xici;

import com.alibaba.fastjson.JSONObject;
import com.chance.cc.crawler.core.CrawlerEnum;
import com.chance.cc.crawler.core.CrawlerRecordContext;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.pipeline.result.CrawlerData;
import com.chance.cc.crawler.core.record.CrawlerRecord;
import com.chance.cc.crawler.core.record.CrawlerRequestRecord;
import com.chance.cc.crawler.core.script.crawler.CrawlerCommonScript;
import com.chance.cc.crawler.core.selector.Json;
import com.chance.cc.crawler.core.selector.Selectable;
import com.chance.cc.crawler.core.tags.LabelTag;
import com.chance.cc.crawler.core.tags.crawler.CrawlerBusinessTags;
import com.chance.cc.crawler.core.tags.crawler.CrawlerResultTags;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerDataType.*;
import static com.chance.cc.crawler.development.scripts.allfeild.AICCommonField.*;

/**
 * @Author Zhao.Hhuan
 * @Date Create in 2021/3/15 13:14
 * @Description 西祠胡同采集脚本
 **/
public class XiCiCrawlerScript extends CrawlerCommonScript {

    private static Logger log = LoggerFactory.getLogger(XiCiCrawlerScript.class);
    private static final String DOMAIN = "xici";
    private static final String SITE = "searchKw";
    private static final String REQUEST_AGAIN_TAG = DOMAIN + "_request_again";
    private static final String SEARCH_KW_SOURCE_URL = "searchKwSourceUrl";

    private static final String PRIFIX = "http://www.xici.net";
    private static final String ENTRANCE_URL = "http://www.xici.net/search";
    private static final String SEARCH_URL = "http://www.xici.net/search/\\d+/\\S*\\?page=\\d+";
    private static final String ITEM_URL = "http://www.xici.net/[a-z0-9]+";
    private static final String COMMENT_SOURCE_URL = "http://www.xici.net/getComment?id=%s&post_user_id=%s&page=1&order=2";
    private static final String COMMENT_URL = "http://www.xici.net/getComment\\S*";
    private static final String COMMENT_REPLY_SOURCE_URL = "http://www.xici.net/getComment?id=%s&post_user_id=%s&per_page=1000&level=2&order=2";

    /**
     * 脚本domain定义
     *
     * @return
     */
    @Override
    public String domain() {
        return DOMAIN;
    }

    /**
     * 进入脚本的正则列表
     */
    @Override
    public void initUrlRegulars() {
        addUrlRegular(ENTRANCE_URL);
        addUrlRegular(SEARCH_URL);
        addUrlRegular(ITEM_URL);
        addUrlRegular(COMMENT_URL);
    }

    /**
     * 是否执行脚本 ： 输入数据检查，合格的才进入脚本
     *
     * @param crawlerRequestRecord
     * @return
     */
    @Override
    public boolean crawlerCheck(CrawlerRequestRecord crawlerRequestRecord) {
        String siteTag = crawlerRequestRecord.tagsCreator().bizTags().getCategoryTag().getKVTagStrVal("site");
        return siteTag.equals(SITE);
    }

    @Override
    public List<CrawlerRecord> prepareRequest(CrawlerRequestRecord requestRecord, List<CrawlerRequestRecord> supportSourceRecords) {
        List<CrawlerRecord> crawlerRecords = new ArrayList<>();
        for (CrawlerRequestRecord supportSourceRecord : supportSourceRecords) {
            String url = supportSourceRecord.getHttpRequest().getUrl();
            if (url.contains("keys")) {
                initKeyword(requestRecord, supportSourceRecord, crawlerRecords);
            }
        }
        return crawlerRecords;
    }

    /**
     * 解析链接方法
     *
     * @param crawlerRequestRecord
     * @param httpPage
     * @return
     */
    @Override
    public List<CrawlerRequestRecord> parseLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerRequestRecord> parsedLinks = new ArrayList<CrawlerRequestRecord>();

        if (!httpPage.isDownloadSuccess() || httpPage.getStatusCode() == 503) {
            log.error(DOMAIN + " page download error!will retry");
            requestAgainCrawlerRecord(parsedLinks, crawlerRequestRecord);
            crawlerRequestRecord.setNeedWashPage(false);
            return parsedLinks;
        }

        if(httpPage.getStatusCode() != 503 && httpPage.getStatusCode() != 200){
            log.error(DOMAIN + httpPage.getStatusCode());
            return parsedLinks;
        }

        String requestUrl = httpPage.getRequest().getUrl();
        if (requestUrl.matches(SEARCH_URL)) {
            searchUrlRecord(crawlerRequestRecord, httpPage, parsedLinks);
        }

        if (requestUrl.matches(ITEM_URL)) {
            itemUrlRecord(crawlerRequestRecord, httpPage, parsedLinks);
        }

        if (requestUrl.matches(COMMENT_URL)) {
            commentUrlRecord(crawlerRequestRecord, httpPage, parsedLinks);
        }

        return parsedLinks;
    }

    private void searchUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks) {
        //未按照时间倒序排列
        String keyword = (String) crawlerRequestRecord.getHttpRequest().getExtras().get("keyword");
        String requestUrl = httpPage.getRequest().getUrl();
        //翻页
        String[] split = requestUrl.split("=");
        String nextPage = split[0] + "=" + (Integer.parseInt(split[1]) + 1);
        CrawlerRequestRecord turnRecord = CrawlerRequestRecord.builder()
                .turnPageRequest(crawlerRequestRecord)
                .httpUrl(nextPage)
                .releaseTime(System.currentTimeMillis())
                .copyBizTags()
                .copyResultTags()
                .build();
        turnRecord.getHttpRequest().setExtras(crawlerRequestRecord.getHttpRequest().getExtras());
        parsedLinks.add(turnRecord);


        //列表页解析
        List<Selectable> nodes = httpPage.getHtml().xpath("//div[@id=\"J-show-board-posts\"]/div").nodes();
        for (Selectable node : nodes) {
            String itemUrl = node.xpath("./div[@class=\"desc\"]/a/@href|./a/@href").get();
            if (StringUtils.isBlank(itemUrl)) {
                continue;
            } else {
                itemUrl = PRIFIX + itemUrl;
            }

            String releaseTime = node.xpath(".//div[@class=\"bottom\"]/div/text()").get();
            if (StringUtils.isBlank(releaseTime) || (StringUtils.isNotBlank(releaseTime) && !releaseTime.contains("|"))) {
                continue;
            } else {
                releaseTime = releaseTime.split("\\|")[1].trim();
            }

            try {
                long releaseTimeToLong = washTime(releaseTime);
                CrawlerRequestRecord itemRecord = CrawlerRequestRecord.builder()
                        .itemPageRequest(crawlerRequestRecord)
                        .httpUrl(itemUrl)
                        .recordKey(itemUrl + keyword)
                        .releaseTime(releaseTimeToLong)
                        .copyBizTags()
                        .copyResultTags()
                        .build();
                itemRecord.setTurnPageFilterInfo(null);
                parsedLinks.add(itemRecord);
            } catch (ParseException e) {
                log.error(e.getMessage());
            }
        }
    }

    private void itemUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks) {
        String requestUrl = httpPage.getRequest().getUrl();
        CrawlerResultTags resultTags = crawlerRequestRecord.tagsCreator().resultTags();
        if (resultTags.hasDataType(comment)) {
            resultTags.getCategoryTag().removeLabelTag("comment");

            CrawlerRequestRecord filterRecord = resultTags.getCategoryTag().getKVTagObjVal("comment_filter_record", CrawlerRequestRecord.class);
            if (filterRecord == null) {
                log.error("filter record can not null !");
                return;
            }

            String comments = httpPage.getHtml().xpath("//div[@class=\"comment-num\"]/span/text()").get();
            //评论数要大于0
            if (StringUtils.isNotBlank(comments) && Integer.parseInt(comments.trim()) > 0) {
                String id = httpPage.getHtml().xpath("//input[@name=\"post_id\"]/@value").get();
                String userId = httpPage.getHtml().xpath("//input[@name=\"user_id\"]/@value").get();
                if (StringUtils.isBlank(id) || StringUtils.isBlank(userId)) {
                    log.error("id or userId is null !");
                    return;
                }
                String url = String.format(COMMENT_SOURCE_URL, id, userId);
                CrawlerRequestRecord commentRecord = CrawlerRequestRecord.builder()
                        .turnPageRequest(crawlerRequestRecord)
                        .httpUrl(url)
                        .releaseTime(System.currentTimeMillis())
                        .notFilterRecord()
                        .copyBizTags()
                        .needWashed(true)
                        .resultLabelTag(comment)
                        .build();
                commentRecord.setFilter(filterRecord.getFilter());
                commentRecord.setFilterInfos(filterRecord.getFilterInfos());
                commentRecord.getHttpRequest().addExtra("articleUrl", requestUrl);
                commentRecord.getHttpRequest().addExtra("userId", userId);
                parsedLinks.add(commentRecord);
            }
        }
    }

    private void commentUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks) {
        //评论翻页
        String requestUrl = httpPage.getRequest().getUrl();
        String[] split = requestUrl.split("\\?");
        String nextUrl = split[0] + "?";
        List<NameValuePair> parse = URLEncodedUtils.parse(split[1], Charset.defaultCharset());
        for (NameValuePair nameValuePair : parse) {
            String name = nameValuePair.getName();
            String value = nameValuePair.getValue();
            if ("page".equals(name)) {
                nextUrl = nextUrl + name + "=" + (Integer.parseInt(value) + 1) + "&";
            } else {
                try {
                    nextUrl = nextUrl + name + "=" + URLEncoder.encode(value, "UTF-8") + "&";
                } catch (UnsupportedEncodingException e) {
                    log.error(e.getMessage());
                }
            }
        }
        nextUrl = nextUrl.substring(0, nextUrl.length() - 1);
        CrawlerRequestRecord commentRecord = CrawlerRequestRecord.builder()
                .turnPageRequest(crawlerRequestRecord)
                .httpUrl(nextUrl)
                .releaseTime(System.currentTimeMillis())
                .copyBizTags()
                .needWashed(true)
                .copyResultTags()
                .build();
        commentRecord.getHttpRequest().setExtras(crawlerRequestRecord.getHttpRequest().getExtras());
        parsedLinks.add(commentRecord);


        //评论的回复
        List<Selectable> nodes = httpPage.getHtml().xpath("//div[@class=\"comment-list-item flex\"]/div").nodes();
        String userId = (String) httpPage.getRequest().getExtras().get("userId");
        for (Selectable node : nodes) {
            String id = node.xpath(".//div[@class=\"flex\"]/@data-id").get();
            List<Selectable> all = node.xpath(".//div[@class=\"secondary-reply\"]/div").nodes();
            if (all == null || all.size() < 1) {
                continue;
            }

            String url = String.format(COMMENT_REPLY_SOURCE_URL, id, userId);
            CrawlerRequestRecord replyRecord = CrawlerRequestRecord.builder()
                    .itemPageRequest(crawlerRequestRecord)
                    .httpUrl(url)
                    .releaseTime(System.currentTimeMillis())
                    .notFilterRecord()
                    .needParsed(false)
                    .needWashed(false)
                    .requestLabelTag(CrawlerEnum.CrawlerRequestType.internalDownload)
                    .build();
            replyRecord.getHttpRequest().addExtra("id", id);
            parsedLinks.add(replyRecord);
        }
    }

    @Override
    public void afterInternalDownload(CrawlerRequestRecord crawlerRecord, List<CrawlerRequestRecord> internalDownloadRecords, List<CrawlerRequestRecord> links) {
        Map<String, List<Map<String, String>>> map = new HashMap<>();
        for (CrawlerRequestRecord internalDownloadRecord : internalDownloadRecords) {
            HttpPage page = internalDownloadRecord.getInternalDownloadPage();
            String key = (String) page.getRequest().getExtras().get("id");
            List<Map<String, String>> replyList = new ArrayList<>();
            List<Selectable> nodes = page.getHtml().xpath("//div[@class=\"secondary-item\"]").nodes();
            for (Selectable node : nodes) {
                Map<String, String> replyMap = new HashMap<>();
                String replyId = node.xpath("./div[@data-id]/@data-id").get();
                String author = node.xpath("./div[@data-id]/span/text()").get();
                author = StringUtils.isNotBlank(author) && author.contains(":") ? author.split(":")[0] : author;
                List<String> all = node.xpath("./div[@data-id]/text()").all();
                StringBuffer contentBf = new StringBuffer();
                for (String data : all) {
                    contentBf.append(data).append(" ");
                }
                String releaseTime = node.xpath("./div[@class=\"floor-num\"]/text()").get();
                replyMap.put("replyId", replyId);
                replyMap.put("author", author);
                replyMap.put("content", contentBf.toString());
                replyMap.put("releaseTime", releaseTime);
                replyMap.put("url", page.getRequest().getUrl());
                replyList.add(replyMap);
            }
            map.put(key, replyList);
        }
        crawlerRecord.getHttpRequest().getExtras().put("replyMap", map);
    }

    @Override
    public List<CrawlerData> washPage(CrawlerRequestRecord crawlerRecord, HttpPage page) {
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        CrawlerResultTags crawlerResultTags = crawlerRecord.tagsCreator().resultTags();

        if (crawlerResultTags.hasDataType(article)) {
            crawlerDataList.add(washArticle(crawlerRecord, page));
        }

        if (crawlerResultTags.hasDataType(interaction)) {
            crawlerDataList.add(washInteraction(crawlerRecord, page));
        }

        if (crawlerResultTags.hasDataType(comment)) {
            crawlerDataList.addAll(washComment(crawlerRecord, page));
        }

        return crawlerDataList;
    }

    private CrawlerData washArticle(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        String itemUrl = httpPage.getRequest().getUrl();
        String articleKey = itemUrl.substring(itemUrl.lastIndexOf("/") + 1);

        String title = httpPage.getHtml().xpath("//h1[@class=\"postDetail-title\"]/text()").get();
        String author = httpPage.getHtml().xpath("//img[@class=\"avatar\"]/parent::div/following-sibling::div[1]/text()").get();
        String authorId = httpPage.getHtml().xpath("//input[@name=\"user_id\"]/@value").get();
        String releaseTime = httpPage.getHtml().xpath("//h1/following-sibling::div[1]/div[1]/div[last()]").get();
        List<String> all = httpPage.getHtml().xpath("//div[@class=\"post-content\"]/p//text()").all();
        StringBuffer conents = new StringBuffer();
        for (String articleText : all) {
            conents.append(articleText).append(" ");
        }

        CrawlerData crawlerData = null;
        try {
            long releaseTimeToLong = washTime(releaseTime);
            crawlerData = CrawlerData.builder()
                    .data(crawlerRequestRecord, httpPage)
                    .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                    .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("article"))
                    .url(itemUrl)
                    .releaseTime(releaseTimeToLong)
                    .addContentKV(Field_Content, conents.toString())
                    .addContentKV(Field_Title, title)
                    .addContentKV(Field_Author, author)
                    .addContentKV(Field_Author_Id, authorId)
                    .build();
        } catch (ParseException e) {
            log.error(e.getMessage());
        }
        return crawlerData;
    }

    private CrawlerData washInteraction(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        String itemUrl = httpPage.getRequest().getUrl();
        String articleKey = itemUrl.substring(itemUrl.lastIndexOf("/") + 1);

        String releaseTime = httpPage.getHtml().xpath("//h1/following-sibling::div[1]/div[1]/div[last()]").get();
        String views = httpPage.getHtml().xpath("//img[@class=\"read-num-img\"]/following-sibling::div/text()").get();
        String likes = httpPage.getHtml().xpath("//img[@class=\"like-num-img J-go-login\"]/following-sibling::div/text()").get();
        String comments = httpPage.getHtml().xpath("//div[@class=\"comment-num\"]/span/text()").get();

        CrawlerData crawlerData = null;
        try {
            long releaseTimeToLong = washTime(releaseTime);
            crawlerData = CrawlerData.builder()
                    .data(crawlerRequestRecord, httpPage)
                    .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                    .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), interaction.enumVal(), articleKey))
                    .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("interaction"))
                    .url(itemUrl)
                    .releaseTime(releaseTimeToLong)
                    .addContentKV(Field_I_Comments, comments)
                    .addContentKV(Field_I_Views, washNum(views))
                    .addContentKV(Field_I_Likes, washNum(likes))
                    .build();
        } catch (ParseException e) {
            log.error(e.getMessage());
        }
        return crawlerData;
    }

    public List<CrawlerData> washComment(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        String requestUrl = httpPage.getRequest().getUrl();
        String articleUrl = (String) httpPage.getRequest().getExtras().get("articleUrl");
        Map<String, List<Map<String, String>>> replyMap = (Map<String, List<Map<String, String>>>) httpPage.getRequest().getExtras().get("replyMap");
        String articleKey = articleUrl.substring(articleUrl.lastIndexOf("/") + 1);

        List<Selectable> nodes = httpPage.getHtml().xpath("//div[@class=\"comment-list-item flex\"]/div").nodes();
        for (Selectable node : nodes) {
            String author = node.xpath(".//div[@class=\"nickName\"]/text()").get();
            String authorId = node.xpath("./div[@data-id]/@data-id").get();
            List<String> all = node.xpath("./div[@class=\"comment-content\"]//text()").all();
            StringBuffer conents = new StringBuffer();
            for (String articleText : all) {
                if (StringUtils.isBlank(articleText)) {
                    continue;
                }
                conents.append(articleText).append(" ");
            }
            String floorAndTime = node.xpath("./div[@class=\"floor-num\"]/text()").get();
            String[] split = floorAndTime.split("&amp;middot;");
            String releaseTime = split[1].trim();
            if (StringUtils.isBlank(releaseTime)) {
                continue;
            }
            String floor = split[0].substring(1, split[0].length() - 1);
            String commentId = node.xpath(".//div[@class=\"flex\"]/@data-id").get();

            String likes = node.xpath(".//div[@class=\"noSelect\"]/text()").get();
            String comments = "0";
            try {
                if (replyMap != null) {
                    List<Map<String, String>> maps = replyMap.get(commentId);
                    if(maps != null){
                        comments = String.valueOf(maps.size());
                        for (Map<String, String> map : maps) {
                            CrawlerData crawlerData = CrawlerData.builder()
                                    .data(crawlerRequestRecord, httpPage)
                                    .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                                    .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), comment.enumVal(), map.get("replyId")))
                                    .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("comment"))
                                    .releaseTime(washTime(map.get("releaseTime")))
                                    .url(map.get("url"))
                                    .requestLabelTag(CrawlerEnum.CrawlerRequestType.filter)
                                    .requestLabelTag(CrawlerEnum.CrawlerRequestType.result)
                                    .addContentKV(Field_Author, map.get("author"))
                                    .addContentKV(Field_Content, map.get("content"))
                                    .addContentKV(Field_Reply_Floor, floor)
                                    .build();
                            crawlerDataList.add(crawlerData);
                        }
                    }
                }
                long releaseTimeToLong = washTime(releaseTime);
                CrawlerData crawlerData = CrawlerData.builder()
                        .data(crawlerRequestRecord, httpPage)
                        .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                        .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), comment.enumVal(), commentId))
                        .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("comment"))
                        .releaseTime(releaseTimeToLong)
                        .url(requestUrl)
                        .requestLabelTag(CrawlerEnum.CrawlerRequestType.filter)
                        .requestLabelTag(CrawlerEnum.CrawlerRequestType.result)
                        .addContentKV(Field_Author, author)
                        .addContentKV(Field_Author_Id, authorId)
                        .addContentKV(Field_Content, conents.toString())
                        .addContentKV(Field_Floor, floor)
                        .addContentKV(Field_I_Likes, likes)
                        .addContentKV(Field_I_Comments, comments)
                        .build();
                crawlerDataList.add(crawlerData);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        return crawlerDataList;
    }


    private long washTime(String time) throws ParseException {
        if (StringUtils.isBlank(time)) {
            return 0;
        }

        LocalDate now = LocalDate.now();
        if (time.matches("\\d{2}-\\d{2} \\d{2}:\\d{2}")) {
            time = now.getYear() + time;
        }
        return DateUtils.parseDate(time, "yyyyMM-dd HH:mm", "yyyy-MM-dd HH:mm").getTime();
    }

    private static String washNum(String text) {
        if (StringUtils.isBlank(text)) {
            return "0";
        }

        text = text.toLowerCase();
        if (text.contains("w")) {
            String[] split = text.split("w");
            String num = String.valueOf(Double.parseDouble(split[0].trim()) * 10000);
            return num.split("\\.")[0];
        }

        return text;
    }

    @Override
    public void afterExecute(CrawlerRecordContext crawlerRecordContext) {

    }

    private void requestAgainCrawlerRecord(List<CrawlerRequestRecord> crawlerRequestRecords, CrawlerRequestRecord crawlerRecord) {
        CrawlerBusinessTags crawlerBusinessTags = crawlerRecord.tagsCreator().bizTags();
        int count = 0;
        if (crawlerBusinessTags.hasKVTag(REQUEST_AGAIN_TAG)) {
            count = (int) crawlerBusinessTags.getCategoryTag().getKVTag(REQUEST_AGAIN_TAG).getVal();
            if (count >= 5) {
                log.error(DOMAIN + " download page the number of retries exceeds the limit" +
                        ",request url {}", crawlerRecord.getHttpRequest().getUrl());
                return;
            }
        }

        String requestUrl = crawlerRecord.getHttpRequest().getUrl();
        LabelTag type = crawlerRecord.tagsCreator().requestTags().getCategoryTag().getLabelTags().get("turn_page_item_request");
        CrawlerRequestRecord crawlerRequestRecord = null;
        if (type == null) {
            crawlerRequestRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRecord)
                    .httpUrl(requestUrl)
                    .releaseTime(crawlerRecord.getReleaseTime())
                    .recordKey(crawlerRecord.getRecordKey() + count)
                    .notFilterRecord()
                    .copyBizTags()
                    .copyResultTags()
                    .build();
        } else {
            crawlerRequestRecord = CrawlerRequestRecord.builder()
                    .itemPageRequest(crawlerRecord)
                    .httpUrl(requestUrl)
                    .releaseTime(crawlerRecord.getReleaseTime())
                    .recordKey(crawlerRecord.getRecordKey() + count)
                    .copyBizTags()
                    .copyResultTags()
                    .build();
        }

        if (crawlerRequestRecord == null) {
            return;
        }

        crawlerRequestRecord.getHttpRequest().setExtras(crawlerRecord.getHttpRequest().getExtras());
        crawlerRequestRecord.getHttpRequest().setHeaders(crawlerRecord.getHttpRequest().getHeaders());
        crawlerRequestRecord.setNeedWashPage(crawlerRecord.isNeedWashPage());
        crawlerRequestRecord.setNeedParsedPage(crawlerRecord.isNeedParsedPage());
        crawlerRequestRecord.tagsCreator().bizTags().addCustomKV(REQUEST_AGAIN_TAG, ++count);
        crawlerRequestRecords.add(crawlerRequestRecord);
    }

    private void initKeyword(CrawlerRequestRecord requestRecord, CrawlerRequestRecord supportSourceRecord, List<CrawlerRecord> crawlerRecords) {
        HttpPage internalDownloadPage = supportSourceRecord.getInternalDownloadPage();
        Map<String, Object> extras = requestRecord.getHttpRequest().getExtras();
        String searchSourceUrl = (String) extras.get(SEARCH_KW_SOURCE_URL);
        if (StringUtils.isBlank(searchSourceUrl)) {
            log.error("search kw source url can not null!");
            return;
        }
        Json json = internalDownloadPage.getJson();
        String msg = json.jsonPath($_type + ".msg").get();
        if (!"success".equals(msg)) {
            log.error("keyword page [{}] download error!", internalDownloadPage.getRequest().getUrl());
            return;
        }

        List<String> all = json.jsonPath($_type + ".content").all();
        for (String data : all) {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String keyword = jsonObject.getString("keyword");

            try {
                String url = String.format(searchSourceUrl, URLEncoder.encode(keyword, "UTF-8"));
                CrawlerRequestRecord turnRecord = CrawlerRequestRecord.builder()
                        .turnPageRequest(requestRecord)
                        .httpUrl(url)
                        .releaseTime(System.currentTimeMillis())
                        .notFilterRecord()
                        .copyBizTags()
                        .copyResultTags()
                        .build();
                turnRecord.tagsCreator().bizTags().addKeywords(keyword);
                turnRecord.getHttpRequest().addExtra("keyword",keyword);
                crawlerRecords.add(turnRecord);
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage());
            }
        }
    }

    public static void main(String[] args) {
        String s = "5.82 W";
        String s1 = washNum(s);
        System.out.println(s1);


    }
}
